package com.hs.car.logger;

import com.ding.operation.OperationFeignClient;
import com.ding.operation.dto.OperationDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author DYF
 * @data 2022-07-26
 * @desc
 */

@Aspect
@Component
public class LogAspect {

    @Autowired(required = false)
    private OperationFeignClient operationFeignClient;

    @Pointcut("@annotation(io.swagger.annotations.ApiOperation )&& (@annotation(org.springframework.web.bind.annotation.GetMapping))")
    public void pointcut() {
    }
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        System.out.println("记录操作日志");
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        // 保存操作日志
        saveLog(point, time);
        System.out.println("执行结果：");
        System.out.println(result);
        return result;
    }
    private void saveLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> aClass = joinPoint.getTarget().getClass();
        Api annotation = aClass.getAnnotation(Api.class);
//        String moduleName = annotation.value();
        String[] tags = annotation.tags();
        String moduleName= tags[0];
        if (moduleName != null) {
            System.out.println("模块：" + moduleName);
        }
        Method method = signature.getMethod();
        ApiOperation logAnnotation = method.getAnnotation(ApiOperation.class);
        if (logAnnotation != null) {
            // 注解上的描述
            System.out.println("操作：" + logAnnotation.value());
        }
        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        System.out.println("方法：" + className + "." + methodName + "()");
        // 请求的方法参数值
        Object[] args = joinPoint.getArgs();
        // 请求的方法参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        // 拼接请求参数
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + ": " + args[i];
            }
            System.out.println("参数：" + params);
        }
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 从获取RequestAttributes中获取HttpServletResponse的信息
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + " " + cookie.getValue());
            }
        }
        System.out.println("请求者的IP：" + request.getRemoteHost());
        int status = response.getStatus();
        System.out.println("http状态码 " + status);
        System.out.println("执行时间：" + time + " 毫秒");



        OperationDto operationDto = new OperationDto();

        operationDto.setOperation(logAnnotation.value());

        operationDto.setIp(request.getRemoteHost());

        String s = operationFeignClient.addLogger(operationDto);

        System.out.println(s);

    }






}
